import http from '@/utils/http'
import { setTokenInfo } from '@/utils/storage'
import { AppDispatch } from '..'
import { Profile, UserAction } from '../reducers/user'

/**
 * 发送短信验证码
 * @param mobile 手机号
 * @returns
 */

export const SendCodes = (mobile: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/sms/codes/${mobile}`)
    console.log(res)
  }
}

/**
 * 登录
 * @param  {{ mobile,code }} values 登录信息
 * @returns thunk
 */
export const Authorizations = ({ mobile, code }: { mobile: string; code: string }) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.post(`/v1_0/authorizations`, { mobile, code })
    console.log(res)
    dispatch({ type: 'user/saveAuth', payload: res.data })
    setTokenInfo(res.data)
  }
}

/**
 * 获取个人用户信息
 * @returns
 */
export const getUserInfo = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/user`)
    console.log(`/v1_0/user`, res)
    dispatch({ type: 'user/saveUser', payload: res.data })
  }
}

/**
 * 获取个人详细资料
 * @returns
 */
export const getUserProfile = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/user/profile`)
    console.log(`/v1_0/user/profile`, res)
    dispatch({ type: 'user/saveProfile', payload: res.data })
  }
}

/**
 * 编辑用户照片资料（头像、身份证照片）
 * @param fd FormData
 * @returns
 */
export const editUserPhoto = (fd: FormData) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.patch(`/v1_0/user/photo`, fd)
    console.log(`/v1_0/user/photo`, res)
    dispatch({ type: 'user/updateProfile', payload: res.data })
  }
}

/**
 * 编辑用户其他资料（通用）
 * @param data Partial<Profile>
 * @returns
 */
export const editUserProfile = (data: Partial<Profile>) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.patch(`/v1_0/user/profile`, data)
    console.log(`/v1_0/user/profile`, res)
    dispatch({ type: 'user/updateProfile', payload: data })
  }
}

/**
 * 清空用户认证信息
 * @param data Profile 其中一个
 * @returns (dispatch: AppDispatch) => Promise<void>
 */
export const clearAuth = (): UserAction => {
  return { type: 'user/clearAuth' }
}
